package com.sibbay.vta;

import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;


public abstract class Favorites {

	private static final String URL = "URL";
	private static final String MAP_URL = "MAP_URL";
	private static final String TITLE = "TITLE";
	private static final String DAY = "DAY";
	
	private static final String FAVORITES_PREF = "favorites";
	
	static void add(final Context ctx, final String key, final String url, final String mapUrl, final String title, final String day) {
		final SharedPreferences pref = ctx.getSharedPreferences(FAVORITES_PREF, 0);
		final SharedPreferences.Editor edit = pref.edit();
		try {
			edit.putString(key, new JSONObject()
					.put(URL, url)
					.put(MAP_URL, mapUrl)
					.put(TITLE, title)
					.put(DAY, day).toString());
			edit.commit();
		} catch (JSONException e) {
			// ignore exception
			e.printStackTrace();	
		}
	}

	static void remove(final Context ctx, final String key) {
		final SharedPreferences pref = ctx.getSharedPreferences(FAVORITES_PREF, 0);
		final SharedPreferences.Editor edit = pref.edit();
		edit.remove(key);
		edit.commit();
	}
	
	static boolean has(final Context ctx, final String station) {
		final SharedPreferences pref = ctx.getSharedPreferences(FAVORITES_PREF, 0);
		return pref.contains(station);
	}
	
	// return array of favorites
	
	static final int ARRAY_TITLE = 0;
	static final int ARRAY_DAY = 1;
	static final int ARRAY_URL = 2;
	
	static String[][] getAsArray(final Context ctx) {
		final SharedPreferences pref = ctx.getSharedPreferences(FAVORITES_PREF, 0);
		final Map<String, ?> all = pref.getAll();
		final String[][] ret = new String[all.size()][];
		int retCnt = 0;
		for (String key: all.keySet()) {
			try {
				final JSONObject obj = new JSONObject(pref.getString(key, null));
				ret[retCnt++] = new String[]{obj.getString(TITLE), obj.getString(DAY), obj.getString(URL)};
			} catch (JSONException e) {
				// ignore
				e.printStackTrace();
			}
		}
		return ret;
	}
	
	static Intent get(final Context ctx, final String key, final Intent intent) {
		final SharedPreferences pref = ctx.getSharedPreferences(FAVORITES_PREF, 0);
		try {
			final JSONObject obj = new JSONObject(pref.getString(key, null));
	        intent.putExtra(RouteListActivity.EXTRA_TITLE, obj.getString(TITLE));
	        intent.putExtra(RouteListActivity.EXTRA_DAY, obj.getString(DAY));
			intent.putExtra(RouteListActivity.EXTRA_URL, obj.getString(URL));
	        intent.putExtra(RouteListActivity.EXTRA_MAP_URL, obj.getString(MAP_URL));
		} catch (JSONException e) {
			e.printStackTrace();
			return null;
		}
		return intent;
	}
}
